const app = getApp();
var a = new Set();
var util = require('../../../../utils/util.js');
var request_api = require('../../../../utils/require_api.js');
const qiniuUploader = require("../../../../utils/qiniuUploader");
const config = require('../../../../config.js')
var timeId=null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgList: [],
    videoList: [],
    upload_img: [],
    indexpicker: '0',
    whoindexpicker: 0, //谁可以看的index
    indexbrand: 0,
    picker: ['图片', '视频'],
    resourseName:'',//资源名称
    relateItemno:'',//关联的款号输入框的值
    osstoken: '', //七牛token
    ossurl: '', //七牛的上传url    
    itemno: [],
    itemIndex: 0,
    searchResultDatas:[],//关联的款号
  },

  //选择上传的类型 图片或者是视频
  PickerChange(e) {
    this.data.videoList = [];
    this.data.imgList = [];
    this.setData({
      indexpicker: e.detail.value,
      imgList: this.data.imgList,
      videoList: this.data.videoList
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    request_api.send(config.uri + '/api/oss/gettoken', {
        "token": wx.getStorageSync('token'),
        "curr_company_key": wx.getStorageSync("company_key"),
      }, //需要传的 data
      function(res) {
        that.data.osstoken = res.data.osstoken;
        that.data.ossurl = res.data.ossurl;
        console.log(that.data.osstoken, that.data.ossurl,"ossurl");
      },
      function(err) {
        console.log(err, "59 uploadpage.js")
      }
    )
  },
//资源名称的输入框
  resourseInput(event){
    this.data.resourseName =event.detail.value;
  },
  //关联款号的输入框点查询
  search1(event){
    this.data.relateItemno = event.detail.value;
    this.data.itemno.push({
      item: this.data.relateItemno
    })
    this.setData({
      itemno: this.data.itemno,
      value: ''
    })
  },
//关联款号输入触发
  searchInput(e){
    console.log(e,"this is e uploadPage searchInput 139");
    if(e.detail.value==''){
      this.setData({
        searchResultDatas: []
      })
      return;
    }
    var that = this;
    timeId && clearTimeout(timeId);
    timeId = setTimeout(() => {
      request_api.request({
        "cmd": 'weixin_api|get_wxproduct_id',
        "paras": [{
          name: "comdition",
          value: e.detail.value
        }]
      }, //需要传的 data
        function (res) {
          that.setData({
            searchResultDatas: res.data.result,
          })
        },
        function () {
          console.log("错误");
        },
      )
    }, 800)
  },

  //点击模糊关键词触发
  itemclick(e) {
    if (e.currentTarget.dataset.condition != '') {
      for (let i = 0; i < this.data.itemno.length; i++) {
        if (this.data.itemno[i].item == e.currentTarget.dataset.condition) {
          wx.showToast({
            title: '已经存在相同的款号',
          })
          setTimeout(() => {
            this.setData({
              itemno: this.data.itemno,
              searchResultDatas: [],
              value: ''
            })
          }, 500)
          return;
        }
      }
      this.data.itemno.push({
        item: e.currentTarget.dataset.condition
      })
      setTimeout(() => {
        this.setData({
          itemno: this.data.itemno,
          searchResultDatas: [],
          value: ''
        })
      }, 400)
    }
  },
 
  //扫一扫
  saoyisao(e) {
    var that = this;
    wx.scanCode({
      onlyFromCamera: false,
      scanType: [],
      success: function(res) {
        request_api.request({
          "cmd": 'weixin_api|get_uniquecode',
          "paras": [{
            name: "comdition",
            value: res.result
          }]
        }, //需要传的 data
          function (e) {
            console.log(e.data.result,"this is uploadPage.js 151page")
            if (e.data.result.length != 0) {
              for (let i = 0; i < that.data.itemno.length; i++) {
                if (res.result == that.data.itemno[i].item) {
                  wx.showToast({
                    title: '已经存在相同款号',
                  })
                  return;
                }
              }
              that.data.itemno.push({
                item: e.data.result[0].goods_no
              })
              that.setData({
                itemno: that.data.itemno
              })
              console.log(that.data.itemno,"that.data.itemno");
            } else if (e.data.result.length == 0) {
              wx.showToast({
                title: '该唯一码没有扫到任何数据',
                icon: 'none'
              })
            }
          },
          function () {
            console.log("错误");
          },
        )
      },
      fail: function(res) {
        wx.showToast({
          title: '扫码失败，请重试',
          icon: 'none',
        })
      }
    })
  },

  hideModal(e) {
    this.data.itemno.splice(this.data.itemIndex, 1);
    this.setData({
      itemno: this.data.itemno,
      modalName: null
    })
  },
  hideModal1(){
    this.setData({
      modalName: null
    })
  },

  //删除关联的款号
  deleteTable(e) {
    this.data.itemIndex = e.target.dataset.itemindex;
    this.setData({
      deleteItem: e.target.dataset.item,
      modalName: e.currentTarget.dataset.target
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  ChooseImage() {
    var that = this;
    if (this.data.indexpicker == 0) {
      wx.chooseImage({
        count: 9, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: (res) => {
          console.log(res.tempFilePaths);
          if (this.data.imgList.length != 0 && (res.tempFilePaths.length + this.data.imgList.length) <= 9) {
            this.setData({
              imgList: this.data.imgList.concat(res.tempFilePaths)
            })
          } else if (this.data.imgList.length == 0) {
            this.setData({
              imgList: res.tempFilePaths
            })
          } else if ((res.tempFilePaths.length + this.data.imgList.length) > 9) {
            this.setData({
              imgList: this.data.imgList.concat(res.tempFilePaths).slice(0, 9)
            })
          }
        }
      });
    } else { //选择视频
      that.data.videoList = [];
      wx.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 15,
        camera: 'back',
        success(res) {
          that.data.videoList.push(res.tempFilePath);
          console.log(that.data.videoList)
          that.setData({
            videoList: that.data.videoList,
            size: (res.size / (1024 * 1024)).toFixed(2)
          })
        }
      })
    }
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '删除',
      content: '确定要删除该文件吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        console.log(e.currentTarget.dataset.index, "你好阿");
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },

  Delvideo() {
    wx.showModal({
      title: '删除',
      content: '确定要删除该文件吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.videoList = []
          this.setData({
            videoList: this.data.videoList
          })
        }
      }
    })
  },

  //上传文件
  upload_btn(res) {
    var that = this;
    var imgList1 = []; //多张图片地址，保存到一个数组当中
    var List = [];
    if (this.data.indexpicker == 0) {
      List = this.data.imgList;
    } else {
      List = this.data.videoList;
    }

    if (List.length == 0) {
      wx.showToast({
        title: '请选择文件进行上传，请重试',
        icon: 'none',
      })
      return;
    } else if (that.data.resourseName==''){
      wx.showToast({
        title: '资源名称不能为空，请重试',
        icon: 'none',
      })
      return;
    } else if (that.data.itemno.length==0) {
      wx.showToast({
        title: '款号不能为空，请重试',
        icon: 'none',
      })
      return;
    }
    wx.showLoading({
      title: '正在上传，请稍后',
      mask: true
    })
    var region = '';
    switch (that.data.ossurl) {
      case 'https://upload.qiniup.com': region = 'ECN'; break;
      case 'https://upload-z1.qiniup.com': region = 'NCN'; break;
      case 'https://upload-z2.qiniup.com': region = 'SCN'; break;
      case 'https://upload-na0.qiniup.com': region = 'NA'; break;
      case 'https://upload-as0.qiniup.com': region = 'ASG'; break;
    }
    if (region==''){
      wx.showToast({
        title: '请求的七牛数据有误，请重试',
        icon: 'none',
      })
      return;
  }
    var state = 0; //state记录当前已经上传到第几张图片
    new Promise(function(resolve, reject) {
      for (var i = 0; i < List.length; i++) {
        qiniuUploader.upload(List[i], (res) => {
          state++;
          imgList1.push(res.imageURL);
          console.log(state)
          if (state == List.length) {
            resolve(imgList1);
          }
        }, (error) => {
          reject('error');
        }, {
            region: region,
          uptoken: that.data.osstoken, // 由其他程序生成七牛 uptoken
        })
      }
    }).then(function(imgList1) {
      console.log(imgList1,"图片都上传成功了哦，接下来就是把数据上传到数据库");
      if (that.data.indexpicker == '0') {
        that.data.imgList = [];
        that.setData({
          imgList: that.data.imgList
        })
      } else {
        that.data.videoList = [];
        that.setData({
          videoList: that.data.videoList
        })
      }
      let subs = [];
      for (let i = 0, tmp = imgList1; i < tmp.length; i++) {
        subs.push({
          pic_name: tmp[i],
          id: i + 1
        })
      }
    var itemno_str='';
    for (let i = 0; i < that.data.itemno.length;i++){
      itemno_str = itemno_str + that.data.itemno[i].item+',';
    }
      console.log(itemno_str, "itemno_str", that.data.resourseName,"resourseName")
      for (let i = 0; i < imgList1.length;i++){
        imgList1[i] = imgList1[i].substr(1);
    }
    request_api.request({
        "cmd": 'weixin_api|insert_wx_resource',
        "paras": [
          { name: "resources_name", value: that.data.resourseName},
          { name: "resources_type", value: parseInt(that.data.indexpicker)==0?1:2 },
          { name: "resources_SH", value: "10201" },
          { name: "resources_class", value: "11203"},
          { name: "is_wx", value:'true' },
          { name: "is_ad", value: 'true'},
          { name: "product_item", value: itemno_str},
          { name: "oss_url", value: imgList1.join(',')},
          { name: "poster", value: '' },
        ]
      }, //需要传的 data
        function (res) {
          wx.showToast({
            title: '上传成功',
            icon: 'none'
          })
          setTimeout(function () {
            wx.hideLoading();
          }, 500);
          that.setData({
            imgList:[],
            videoList:[],
            resourseName:'',
            resourcevalue:'',
            itemno:[]
          })
        },
        function () {
          console.log("错误");
        },
      )
    })
  },
})